package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.sso.mapper.UserMapper;
import com.tanhua.sso.pojo.User;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
@Slf4j
public class UserService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    public String login(String phone,String code){
        String redisKey = "CHECK_CODE_" + phone;
        boolean isNew = false;

        String redisData  = this.redisTemplate.opsForValue().get(redisKey);
        if(!StringUtils.equals(code,redisData)){
            return null;
        }

        this.redisTemplate.delete(redisKey);

        LambdaQueryWrapper<User> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper.eq(User::getMobile,phone);
        User user = this.userMapper.selectOne(objectLambdaQueryWrapper);

        if (null==user){
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));

            this.userMapper.insert(user);
            isNew=true;
        }

        HashMap<String, Object> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("id",user.getId());
        String compact = Jwts.builder()
                .setClaims(stringStringHashMap)
                .signWith(SignatureAlgorithm.HS256, secret)
                .setExpiration(new DateTime().plusDays(30).toDate())
                .compact();

        try {
            HashMap<String, Object> msg = new HashMap<>();
            msg.put("id",user.getId());
            msg.put("date",System.currentTimeMillis());
            this.rocketMQTemplate.convertAndSend("tabhua-sso-login",msg);
        } catch (MessagingException e) {
            log.error("发送消息失败",e);
        }
        return compact + "|" + isNew;
    }

    public User queryUserByToken(String token) {
            return null;
            //TODO
    }
}
